package com.javaee.web.servlet;
import java.io.IOException;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javaee.ejb.entity.Employee;
import com.javaee.ejb.entity.Project;
import com.javaee.ejb.session.remote.EmployeeManagerRemote;
import com.javaee.ejb.session.remote.ProjectManagerRemote;
import com.javaee.web.HttpServletBase;
import com.javaee.web.SiteParameters;

/**
 * Servlet implementation class AttachEmployee
 */
public class AttachEmployeeServlet extends HttpServletBase {
	private static final long serialVersionUID = 1L;

	@EJB
	private ProjectManagerRemote projectManager;
	@EJB
	private EmployeeManagerRemote employeeManager;

	/**
	 * @see HttpServletBase#HttpServletBase()
	 */
	public AttachEmployeeServlet() {
		super();
	}

	@Override
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		String[] employeesId = request.getParameterValues("employeesId");

		// Chargement du project avec ses employes
		Project project = projectManager.getByIdWithMembers(projectId);

		if (project.getMembers() == null) {
			project.setMembers(new ArrayList<Employee>());
		}

		if (employeesId != null) {
			Employee employee;
			for (String id : employeesId) {
				employee = employeeManager.getById(Integer.parseInt(id));
				project.getMembers().add(employee);
			}

			// Sauvegarde
			projectManager.saveProject(project);
		}

		response.sendRedirect(SiteParameters.getFullServletPath("project")
				+ "?projectId=" + projectId);
	}
}
